package com.xpec.c4.service.utility.encrypt;

/**
 * 
 * @author yangbingyan
 *
 */
public class XKey {

	/**
	 * 16bytes
	 */
	public static final int MAX_KEY_LENGTH = 16;
	
	/**
	 * 
	 */
	private byte [] key;	
	
	/**
	 * 
	 * @param s
	 * @param limit_count
	 * @return
	 */
	private byte[] static_stringToByteArray(String s, int limit_count){
		
		// String::getBytes 會把char轉成byte,<br>
		// Java的char不一定是1-byte或 2-bytes...Uft8的char滿多是3-bytes或更大,<br>
		// 所以只直接取string轉出來的來使用<br>
		byte[] tmpStr = s.getBytes();
		
		// 密碼長度太长要切短<br>
		// 我也来两层的～		
		int lmcount = (tmpStr.length > limit_count) ? ( (limit_count > MAX_KEY_LENGTH) ? MAX_KEY_LENGTH
				: limit_count )
				: ( tmpStr.length );

		// 不足KEY_LENGTH的要补足
		int fillCount = (lmcount < MAX_KEY_LENGTH) ? MAX_KEY_LENGTH - lmcount: 0;
		
		byte[] temp = new byte[lmcount + fillCount];
		
		for(int i = 0 ; i < lmcount ; i++){
			temp[i] = tmpStr[i];
		}
		
		return temp;
	}	

	public XKey(){	
	}
	
	public XKey(byte [] key){	
		setKey(key);
	}
	
	public XKey(String key){	
		setKey(key);
	}

	public byte [] getKey() {
		return key;
	}

	public void setKey(byte [] key) {
		
		if(key.length == MAX_KEY_LENGTH){
			this.key = key;
			return;
		}
		
		this.key = new byte[MAX_KEY_LENGTH];

		int len = (key.length > MAX_KEY_LENGTH)? MAX_KEY_LENGTH : key.length; 

		for(int i = 0 ; i < len ; i++){
			this.key[i] = key [i];
		}
	}
	
	public void setKey(String string){
		this.key = static_stringToByteArray(string, MAX_KEY_LENGTH);		
	}

}
